#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <string>
#include <mutex> // 添加头文件以使用互斥锁

using namespace std;

// 创建一个互斥锁对象用于同步对cout的访问
std::mutex mtx;

int x = 100;

void show(const string &name)
{
    // 锁定互斥锁，确保一次只有一个线程可以输出
    std::lock_guard<std::mutex> lock(mtx);

    cout << name << ",pid:" << getpid() << " " << x << endl << endl;
}

void *threadRun(void *args)
{
    const string name = (char *)args;
    while (1)
    {
        show(name);
        sleep(1);
    };
    return nullptr;
}

int main()
{
    pthread_t tid[5];
    char name[64];
    for (int i = 0; i < 5; i++)
    {
        snprintf(name, sizeof(name), "%s-%d", "thread", i);
        pthread_create(tid + i, nullptr, threadRun, (void *)name);
        sleep(1);
    }

    // 主线程也进行循环输出
    while (true)
    {
        cout << "main thread, pid: " << getpid() << endl;
        sleep(3);
    }

    return 0;
}